<template>
  <div class="mx-[25px] sm:m-[30px_14px] xl:m-[50px]">
    <div v-if="title" class="flex items-baseline mb-[15px] xl:mb-[20px]">
      <h2 v-if="title" class="text-[18px] xl:text-[24px]">
        {{ title }}
      </h2>
    </div>

    <div class="flex flex-wrap">
      <Card
        class="w-full sm:w-[calc(100%/2)] p-1 md:w-[calc(100%/3)] md:p-2 lg:w-[calc(100%/4)] xl:w-[calc(100%/6)] 2xl:w-[calc(100%/6)]"
        v-for="item in items.results"
        :key="`card-${item.id}`"
        :item="item"
      />
    </div>

    <div
      v-if="items.page < items.total_pages"
      class="py-10 flex items-center w-full justify-center"
    >
      <div v-if="loading">
        <RiLoaderLine class="fill-primary animate-spin" />
      </div>
    </div>
  </div>
</template>
<script setup>
import { useDebounceFn, useEventListener } from "@vueuse/core";
import { RiLoaderLine } from "vue-icons-plus/ri";
import Card from "./Card.vue";

const { title, items, loading } = defineProps({
  title: {
    type: String,
    required: false,
    default: "",
  },

  items: {
    type: Object,
    required: true,
  },

  loading: {
    type: Boolean,
    required: false,
    default: false,
  },
});

const emit = defineEmits(["loadMore"]);

const debouncedFn = useDebounceFn(() => {
  if (items.page < items.total_pages) {
    const bottomOfWindow =
      window.innerHeight + window.pageYOffset >=
      document.body.offsetHeight - 600;
    if (bottomOfWindow && !loading) {
      loadMore();
    }
  } else {
    window.removeEventListener("scroll", debouncedFn);
  }
}, 100);

useEventListener(window, "scroll", debouncedFn);

const loadMore = () => {
  emit("loadMore");
};
</script>
